package edu.ucsd.ccdb.rightClickPopupUtil;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import edu.ucsd.ccdb.MainConfiguration;
import edu.ucsd.ccdb.generalDataType.TagDataValue;
import edu.ucsd.ccdb.servlet.ServletSendReceive;
import edu.ucsd.irods.IRODSFileString;
import edu.ucsd.irods.SQLDBQuery;

public class RemoveAllCCDBTagsListener implements ActionListener{

	private JTree tree;
	private Integer MPID;
	private JFrame frame;
	
	
	public RemoveAllCCDBTagsListener ( Integer MPID, JTree tree, JFrame frame) {
		this.MPID = MPID;
		this.tree = tree;
		this.frame = frame;
	}
	
	public void actionPerformed(ActionEvent e) {

		// get the select node
		TreePath selectedPath = tree.getSelectionPath() ;
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
			
		IRODSFileString file = (IRODSFileString) node.getUserObject();
		//---------------------------------------------------------
		
		List <TagDataValue> listData1 = getDetailTabsOnSelectedFile(file.getAbsolutePath());
		
		try {
			for (TagDataValue dataValue: listData1)	// there only 1 tag, legacy code here 
				SQLDBQuery.removeTagCCDB(MPID, file, dataValue.getData() );
		}catch (Exception e1) {
			e1.printStackTrace();
		}
		
		if (file.isDirectory()) {
		
			Queue<IRODSFileString> queue = new PriorityQueue<IRODSFileString>();
			queue.offer(file);
			
			IRODSFileString iterateFile = null;
			while ( (iterateFile = queue.poll()) != null  ) {
				
				String query = MainConfiguration.SERVLET_SERVER + MainConfiguration.SERVLET_PARAMETER + iterateFile.getAbsolutePath();
				List<IRODSFileString> listFiles = ServletSendReceive.getResponse( query );
		
				for (IRODSFileString element: listFiles) {
				
					if ( element.isDirectory() ) 
						queue.offer(element);
					
					List <TagDataValue> listData = getDetailTabsOnSelectedFile(element.getAbsolutePath());
				
					try {
						for (TagDataValue dataValue: listData)	// there only 1 tag, legacy code here 
							SQLDBQuery.removeTagCCDB(MPID, element, dataValue.getData() );
					}catch (Exception e1) {
						e1.printStackTrace();
					}
				}
			}
		}
		
		JOptionPane.showMessageDialog(frame, "All CCDB tags has been deleted", "Delete successfull", JOptionPane.INFORMATION_MESSAGE);
	}
	
	private List<TagDataValue> getDetailTabsOnSelectedFile (String filePath ) {
		
		List<TagDataValue> data = null;
		try {
			data = SQLDBQuery.getSumaryInfo(filePath);
		} catch (Exception e) {
			e.printStackTrace();			
		}
		
		return data;
	}

}
